from pyexpat.errors import messages
from flask import Flask,request,jsonify
from flask_cors import CORS
from models import *

app = Flask(__name__)

#配置当前应用支持跨域请求
CORS(app)

#配置数据库
# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost:3306/flask_demo'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db.init_app(app)
#建表
with app.app_context():
    db.create_all()

#注册
@app.route('/register', methods=['POST'])
def register():
    try:
        # 接收数据
        username = request.get_json().get('userName')
        password = request.get_json().get('password')
        # 判断用户名是否已经存在
        user = User.query.filter_by(username=username).first()
        if user:
            return jsonify({'success': False, 'messages': '用户名已经存在'})
        else:
            # 创建用户
            password = User.set_password(password)
            user = User(username=username, password_hash=password)
            # 保存到数据库
            db.session.add(user)
            db.session.commit()
            return jsonify({'success': True, 'messages': '注册成功'})

    except Exception as e:
        print(e)
        return jsonify({'success': False,'message':'注册失败'})

@app.route('/login', methods=['POST'])
def login():
    try:
        username = request.get_json().get('userName')
        password = request.get_json().get('password')
        user = User.query.filter_by(username=username).first()
        if (user):
            if (user.check_password(password)):
                return jsonify({'success': True, 'messages': '登录成功','user':user.to_dict()})
            else:
                return jsonify({'success': False, 'messages': '密码错误'})
        else:
            return jsonify({'success': False, 'messages': '用户名不存在'})
    except Exception as e:
        print(e)
        return jsonify({'success': False,'message':'登录失败'})

#查询当前登录人的好友
@app.route('/get_friends', methods=['GET'])
def get_riends():
    try:
        user_id = request.args.get('userId')
        friends_list = Friend.query.filter_by(user_id=user_id).all()
        return jsonify({'success': True, 'friends': [f.to_dict() for f in friends_list]})
    except Exception as e:
        print(e)
        return jsonify({'success': False,'message':'查询好友失败'})
@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!'


if __name__ == '__main__':
    app.run()
